package com.algento.jnitest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.TextView;

import com.algento.jnitest.databinding.ActivityMainBinding;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {

    // Used to load the 'jnitest' library on application startup.
    static {
        System.loadLibrary("jnitest");
    }
    private BufferedWriter cacheFileWriter;
    private ActivityMainBinding binding;
    int i = 0;
    private volatile boolean mIsPlaying = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Student[] stu = new Student[3];
        stu[0] = new Student();
        stu[0].setId("0");
        stu[0].setName("ansionHui");
        // Example of a call to a native method
        TextView tv = binding.sampleText;
        saveLastCameraBitmap();
        tv.setOnClickListener(view->{
            test();
        });
//        binding.surfaceView.getHolder().addCallback(this);
    }

    private void test() {
//        try {
//            String hello = getCacheFilePath("hello");
//            Log.d("ansion",hello);
//            FileOutputStream output = openFile4Write(hello, false);
//            cacheFileWriter = new BufferedWriter(new OutputStreamWriter(output, Charset.forName("UTF-8")));
//
//            // 以json方式写入BaseEvent
//            cacheFileWriter.write("GsonUtil.toJson(event)"+(++i));
//            cacheFileWriter.flush();
//        } catch (IOException e) {
//           e.printStackTrace();
//        }
//        Bitmap bitmap = Bitmap.createBitmap(getResources().getDisplayMetrics(),
//                100, 100, Bitmap.Config.ARGB_8888);
    }
    private void saveLastCameraBitmap() {
        try {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.testansion);
            if (bitmap != null) {
                Log.d("ansion","bitmap is not null");
                Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight());
                int realHeith = (int) (newBitmap.getHeight() / (newBitmap.getWidth() / 80.0f));
                Bitmap lastBitmap = Bitmap.createScaledBitmap(newBitmap, 80, realHeith, true);
                if (lastBitmap != null) {
                    Log.d("ansion","lastBitmap is not null");

                    byte[] bytes = Utils.bitmapToByteArray(lastBitmap);
//                    Utils.blurBitmap(bytes, 3, 1, bitmap.getWidth(), bitmap.getHeight(), bitmap.getRowBytes());
                    Utils.blurBitmap(bytes, 7, 1, lastBitmap.getWidth(), lastBitmap.getHeight(), lastBitmap.getRowBytes());
                    Log.d("ansion","lastBitmap width:"+lastBitmap.getWidth()+",bytes:"+lastBitmap.getRowBytes());
                    Bitmap tempBitmap = Utils.byteArrayToBitmap(bytes, 80, realHeith);
                    Log.d("ansion","tempBitmap width:"+tempBitmap.getWidth());
                    File file = new File(getApplicationContext().getFilesDir(), "cthumb" + 1 + ".jpg");
                    Log.d("ansion","file path:"+file.getAbsolutePath());
                    FileOutputStream stream = new FileOutputStream(file);
                    tempBitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream);
                    binding.imageBlur.setVisibility(View.VISIBLE);
                    binding.imageBlur.setImageBitmap(tempBitmap);
                    bitmap.recycle();
                    newBitmap.recycle();
                    lastBitmap.recycle();
                }

            }
        } catch (Throwable ignore) {

        }
    }
    public static FileOutputStream openFile4Write(String pathName, boolean bAppend) {
        File file = new File(pathName);
        FileOutputStream fos = null;

        if (file.exists() && bAppend == false) {
            file.delete();
        }
        try {
            File pf = file.getParentFile();
            pf.mkdirs();//避免进程运行过程中删除SD卡目录
            fos = new FileOutputStream(file, bAppend);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fos;
    }
    public String getCacheFilePath(String fileName) {
        if (null == fileName) {
            return fileName;
        }

        String sdcard = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ?
                getExternalFilesDir(this).getAbsolutePath() : getFilesDir().getAbsolutePath();

        String realfile = null;

        if (isSDCardAvailable()) {
            realfile = sdcard + fileName;
            File f = new File(realfile);
            if (f.exists() == false) {
                realfile = getDataRootPath() + fileName;

            }
        } else {
            realfile = getDataRootPath() + fileName;

        }
        new File(realfile).getParentFile().mkdirs();
        return realfile;

    }
    public boolean isSDCardAvailable() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }
    private String getDataRootPath() {
        String pkgName = getPackageName();
        return getCacheDir().getAbsolutePath() + "/" + pkgName + "/";
    }

    private File getExternalFilesDir(Context context) {
        File dir = context.getExternalFilesDir((String) null);
        if (dir != null) {
            return dir;
        }

        return context.getFilesDir();
    }

    //ffmpeg start
    public native int init(Surface surface);
    public native void play(String path);
    public native void stop();

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        if (mIsPlaying) {
            return;
        }
        mIsPlaying = true;
        holder.setFormat(PixelFormat.RGBA_8888);
        init(holder.getSurface());
        // 获取外部存储中的图片目录
        String picturesDir = Environment.getExternalStorageDirectory().getPath();
        String path = picturesDir+File.separator+"normalvideo.mp4";
        File file = new File(path);
        if (file.exists()) {
            Log.d("ANSION","MAINACTIVITY PATH:"+path);
            play(path);
        }
    }


    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
        Log.d("ANSION","surfaceChanged:"+format);
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        stop();
    }

    //ffmpeg end
}